'use strict';

const path = require("path");
const glob = require('glob');

//路径定义
const srcDir = path.resolve(process.cwd(), 'src');
const distDir = path.resolve(process.cwd(), 'dist');
const nodeModPath = path.resolve(__dirname, './node_modules');
const publicPath = '/';//发布到服务器的文件夹

//插件定义
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const cleanWebpackPlugin = require('clean-webpack-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');

//入口文件定义
const entries = function () {
  let jsDir = path.resolve(srcDir, 'js');
  let entryFiles = glob.sync(jsDir + '/*.{js,jsx}');
  let map = {};

  for (let i = 0; i < entryFiles.length; i++) {
    let filePath = entryFiles[i];
    let filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'));
    map[filename] = filePath;
  }
  return map;
}

//html_webpack_plugins 定义
const html_plugins = function () {
  let entryHtml = glob.sync(srcDir + '/*.ejs');
  let r = [];
  let entriesFiles = entries();
  for (let i = 0; i < entryHtml.length; i++) {
    let filePath = entryHtml[i];
    let filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'));
    let conf = {
      template: filePath,
      filename: filename + '.html'
    };
    //如果和入口js文件同名
    if (filename in entriesFiles) {
      conf.inject = 'body';
      conf.chunks = ['vendor', filename];
    }
    //跨页面引用，如pageA,pageB 共同引用了common-a-b.js，那么可以在这单独处理
    //if(pageA|pageB.test(filename)) conf.chunks.splice(1,0,'common-a-b')
    r.push(new HtmlWebpackPlugin(conf));
  }
  return r
}

module.exports = function (options) {
  options = options || {};
  const debug = options.debug !== undefined ? options.debug : true;

  let plugins = [];

  plugins.push(new MiniCssExtractPlugin({
    filename: debug ? 'css/[name].css' : 'css/[name].[hash].css',
    chunkFilename: debug ? 'css/[id].css' : 'csss/[id].[hash].css'
  }))

  if (!debug) plugins.push(new cleanWebpackPlugin());

  //config
  const config = {
    mode: debug ? 'development' : 'production',
    entry: Object.assign(entries(), {
      // 用到什么公共lib（例如jquery.js），就把它加进vendor去，目的是将公用库单独提取打包
      'vendor': ['jquery', 'bootstrap']
    }),
    output: {
      path: path.join(__dirname, "dist"),
      filename: "js/[name].[hash].js",
      chunkFilename: '[chunkhash:8].chunk.js',
      publicPath: publicPath
    },
    optimization: {
      minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          loader: 'babel-loader',
          include: [srcDir]
        },
        {
          test: /\.((woff2?|svg)(\?v=[0-9]\.[0-9]\.[0-9]))|(woff2?|svg|jpe?g|png|gif|ico)$/,
          use: [
            //小于10KB的图片会自动转成dataUrl，
            'url-loader?limit=10000&name=img/[hash:8].[name].[ext]'
          ]
        },
        {
          test: /\.((ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9]))|(ttf|eot)$/,
          use: 'url-loader?limit=10000&name=fonts/[hash:8].[name].[ext]'
        },
        {
          test: /\.(tpl|ejs)$/,
          use: 'ejs-loader'
        },
        {
          test: /\.(sa|sc|c)ss$/,
          use: [
            {
              loader: MiniCssExtractPlugin.loader,
              options: {
                hmr: process.env.NODE_ENV === 'development'
              }
            },
            'css-loader',
            'postcss-loader',
            'sass-loader'
          ],
        },
      ]
    },
    resolve: {
      extensions: ['.js', '.css', '.scss', '.tpl', '.png', '.jpg'],
      modules: [srcDir, nodeModPath],
      alias: {
        "_": "loadsh",
        'common': 'js/lib/common.js',
        "commonCss": "css/common.sass",
        '@': path.join(__dirname, 'src')
      }
    },
    plugins: plugins.concat(html_plugins())
  }

  return config;
}
